package com.avic.rong.fragment;

import android.content.Intent;
import android.graphics.Color;
import android.os.Bundle;
import android.support.annotation.NonNull;
import android.support.v4.app.Fragment;
import android.support.v4.app.FragmentManager;
import android.support.v4.app.FragmentPagerAdapter;
import android.support.v4.view.ViewPager;
import android.text.TextUtils;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ImageView;
import android.widget.Toast;

import com.avic.rong.BaseFragment;
import com.avic.rong.MainActivity;
import com.avic.rong.R;
import com.avic.rong.activity.login.LoginPhoneActivity;
import com.avic.rong.bean.show_bean.ChannelData;
import com.avic.rong.bean.show_bean.ChannelListBean;
import com.avic.rong.course.FragmentCultivate;
import com.avic.rong.course.showapi.ChannelListApi;
import com.avic.rong.questionOrAnswer.activity.QuestionActivity;
import com.avic.rong.search.activity.SearchHomePageActivity;
import com.avic.rong.utils.ConstantsUtils;
import com.avic.rong.utils.DateUtils;
import com.avic.rong.utils.SharedPreferencesUtil;
import com.avic.rong.utils.ToastTools;
import com.example.minato.minastore.BaseResultEntity;
import com.example.minato.minastore.http.HttpManager;
import com.example.minato.minastore.listener.HttpOnNextListener;
import com.flyco.tablayout.SlidingTabLayout;
import com.flyco.tablayout.listener.OnTabSelectListener;
import com.google.gson.Gson;
import com.google.gson.reflect.TypeToken;
import com.orhanobut.logger.Logger;

import java.lang.reflect.Type;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import butterknife.BindView;
import butterknife.OnClick;

public class FragmentHomeLayzed extends BaseFragment implements OnTabSelectListener {

    private static final String ARG_PARAM1 = "param1";
    private static final String ARG_PARAM2 = "param2";
    @BindView(R.id.imag_rr)
    ImageView imagReturn;
    @BindView(R.id.img_publish)
    ImageView textViewSearchCancel;

    public static ViewPager viewPager;

    @BindView(R.id.tab_layout)
    SlidingTabLayout tab_layout;
    //@BindView(R.id.resetload)
//    LinearLayout resetload;
//    @BindView(R.id.no_network_reload_btn)
//    StateButton no_network_reload_btn;
//    @BindView(R.id.loading_layout)
//    LoadingLayout loading_layout;

    private BaseResultEntity<ChannelListBean> baseResultEntity = new BaseResultEntity<>();
    private List<String> titleList = new ArrayList<>();
    private List<ChannelData> channelDataList = new ArrayList<>();

    public MyFragmentPagerAdapter fragmentPagerAdapter;
    //    public static KnowledgePagerAdapter knowledgePagerAdapter;
    public String fixedLocation = "推荐";//linkme skip

    public FragmentHomeLayzed() {
    }

    public static FragmentHomeLayzed newInstance(String param1, String param2) {
        FragmentHomeLayzed fragment = new FragmentHomeLayzed();
        Bundle args = new Bundle();
        fragment.setArguments(args);
        return fragment;
    }

 /*   @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container,
                             Bundle savedInstanceState) {
        //第二次加载的时候重复调用了onCreateView()这个方法，重新new了一个pageadapter导致子fragment不显示
        if (rootView != null) {
            ViewGroup parent = (ViewGroup) rootView.getParent();
            if (parent != null) {
                parent.removeView(rootView);
            }
            return rootView;
        }
        rootView = inflater.inflate(R.layout.fragment_fragment_home, container, false);

//        View rootView = inflater.inflate(R.layout.fragment_fragment_home, container, false);
        viewPager = rootView.findViewById(R.id.view_pager);
        ButterKnife.bind(this, rootView);
        tab_layout = rootView.findViewById(R.id.tab_layout);
        tabList = new ArrayList<>();
        list = new ArrayList<>();
        knowledgePagerAdapter = new KnowledgePagerAdapter(getChildFragmentManager());
        viewPager.setAdapter(knowledgePagerAdapter);
        initData();
        return rootView;
    }*/

//    @Override
//    public void onResume() {
//        super.onResume();
//        if (tabList.size() < 1) {
//            initData();
//        }
//    }


    @Override
    protected void initView() {
    /*    //第二次加载的时候重复调用了onCreateView()这个方法，重新new了一个pageadapter导致子fragment不显示
        if (rootView != null) {
            ViewGroup parent = (ViewGroup) rootView.getParent();
            if (parent != null) {
                parent.removeView(rootView);
            }
            return rootView;
        }
        rootView = inflater.inflate(R.layout.fragment_fragment_home, container, false);*/

//        View rootView = inflater.inflate(R.layout.fragment_fragment_home, container, false);
        viewPager = fragmentView.findViewById(R.id.view_pager);
//        tabList = new ArrayList<>();
//        list = new ArrayList<>();
//        knowledgePagerAdapter = new KnowledgePagerAdapter(getChildFragmentManager());
        fragmentPagerAdapter = new MyFragmentPagerAdapter(getChildFragmentManager());
//        viewPager.setAdapter(knowledgePagerAdapter);
        viewPager.setAdapter(fragmentPagerAdapter);

        tab_layout.setIndicatorColor(Color.rgb(152, 199, 39));
        tab_layout.setTextSelectColor(Color.rgb(152, 199, 39));
        tab_layout.setTextBold(2);

        ChannelListApi channelListApi = new ChannelListApi((MainActivity) getActivity(), httpOnNextListener);
        channelListApi.setCache(true);
        HttpManager.getInstance().doHttpDeal(channelListApi);
    }

    @Override
    protected void addListener() {

    }

    @Override
    protected int getContentViewId() {
        return R.layout.fragment_fragment_home;
    }


    //提问
    @OnClick({R.id.tv_question, R.id.ll_group_publish})
    public void onQuestion(View view) {
        if (!SharedPreferencesUtil.isLogin()) {
            ToastTools.showToast("登录后才可发布");
            startActivity(new Intent(getActivity(), LoginPhoneActivity.class));
            return;
        }
        if (DateUtils.isFastDoubleClick()) return;
        startActivity(QuestionActivity.queryIntent(getActivity(), null));
    }


    @OnClick({R.id.shop_search_Text})
    public void clickListener(View view) {
        int viewId = view.getId();
        switch (viewId) {
            case R.id.shop_search_Text:
                getActivity().startActivity(SearchHomePageActivity.getIntent(getContext(), SearchHomePageActivity.class));
                break;
        }
    }


    HttpOnNextListener<BaseResultEntity<ChannelListBean>> httpOnNextListener = new HttpOnNextListener<BaseResultEntity<ChannelListBean>>() {
        @Override
        public void onNext(BaseResultEntity<ChannelListBean> baseResultEntity) {

            if (ConstantsUtils.STATUS_SUCCESS_200.equals(baseResultEntity.getCode())) {
//                loading_layout.setStatus(LoadingLayout.SUCCESS);
                if (baseResultEntity.getData() == null) return;
                channelDataList.clear();
                channelDataList.addAll(baseResultEntity.getData().getChannelList());
//                //关注默认channelId=100
//                if (!list.contains("关注")) {
//                    list.add("关注");
////                    list.add("视频");
//                    tabList.add(new ChannelBean("100", "关注"));
////                    tabList.add(new ChannelBean("101", "视频"));
//                }
//
//                for (int i = 0; i < size; i++) {
//                    String channelName = channelListBean.getData().getChannelList().get(i).getChannelName();
//                    int channelId = channelListBean.getData().getChannelList().get(i).getChannelId();
//                    if (!list.contains(channelName)) {
//                        list.add(channelName);
//
//                        tabList.add(new ChannelBean(channelId + "", channelName));
//                    }
//                }
//
//                mTitles = list.toArray(new String[list.size()]);
            }

            updateTabView();
        }

        @Override
        public void onCacheNext(String cacheString) {
//            loading_layout.setStatus(LoadingLayout.SUCCESS);
            try {
                Gson gson = new Gson();
                Type type = new TypeToken<BaseResultEntity<ChannelListBean>>() {
                }.getType();
                BaseResultEntity resultEntity = gson.fromJson(cacheString, type);

                if (ConstantsUtils.STATUS_SUCCESS_200.equals(resultEntity.getCode())) {
//                    loading_layout.setStatus(LoadingLayout.SUCCESS);
                    channelDataList.clear();
                    channelDataList.addAll(((ChannelListBean) resultEntity.getData()).getChannelList());
                }

                updateTabView();
            } catch (Exception e) {
//                loading_layout.setStatus(LoadingLayout.ERROR);
            }
        }

        @Override
        public void onError(Throwable e) {
//            if (e instanceof SocketTimeoutException || e instanceof ConnectException) {
//                loading_layout.setStatus(LoadingLayout.NO_NETWORK);
//            } else {
//                loading_layout.setStatus(LoadingLayout.ERROR);
//            }
            updateTabView();
        }
    };


    //定位到tab
    private void updateTabView() {

        ChannelData data = new ChannelData();
        data.setChannelId(100);
        data.setChannelName("关注");
        channelDataList.add(0, data);

        fragmentMap.clear();
        titleList.clear();
        for (ChannelData channelData : channelDataList) {
            titleList.add(channelData.getChannelName());
        }

        fragmentPagerAdapter.notifyDataSetChanged();
//        viewPager.setOffscreenPageLimit(titleList.size());
        tab_layout.setViewPager(viewPager, titleList.toArray(new String[titleList.size()]));


//        for(int position = 0; position < channelDataList.size(); position++){
//            if (channelDataList.get(position).getChannelName().equals("推荐")) {
//                tempFragment = FragmentRecommend.getInstance(channelDataList.get(position).getCode(), channelDataList.get(position).getChannelName(), getActivity());
//
//            } else if (channelDataList.get(position).getChannelName().equals("成果转化")) {
//                tempFragment = FragmentAchievements.getInstance(channelDataList.get(position).getChannelName(), getActivity());
//
//            } else if (channelDataList.get(position).getChannelName().equals("关注")) {
//                tempFragment = FragmentFollow.getInstance(channelDataList.get(position).getChannelName(), getActivity());
//
//            } else if (channelDataList.get(position).getChannelName().equals("世界标准日")) {
//                tempFragment = FragmentFollow.getInstance(channelDataList.get(position).getChannelName(), getActivity());
//
//            } else if (channelDataList.get(position).getChannelName().equals("培训")) {
//                tempFragment = FragmentCultivate.getInstance(channelDataList.get(position).getChannelName(), getActivity());
//
//            } else if (channelDataList.get(position).getChannelName().equals("问答")) {
//                tempFragment = FragmentWenDa.getInstance(channelDataList.get(position).getChannelName(), getActivity());
//
//            } else {
//                tempFragment = FragmentRecommend.getInstance(channelDataList.get(position).getCode(), channelDataList.get(position).getChannelName(), getActivity());
//            }
//            fragmentMap.put(position,tempFragment);
//        }



        int tempIndex = 1;
        for (int index = 0; index < channelDataList.size(); index++) {
            if (!TextUtils.isEmpty(fixedLocation) && fixedLocation.equals(channelDataList.get(index).getChannelName())) {
                tempIndex = index;
            }
        }
        Logger.i("----------------------fixed:" + fixedLocation);
        if (channelDataList.size() > 1){
            tab_layout.setCurrentTab(tempIndex);
        }

    }


    @Override
    public void onTabSelect(int position) {
        Toast.makeText(getActivity(), "onTabSelect&position--->" + position, Toast.LENGTH_SHORT).show();
    }

    @Override
    public void onTabReselect(int position) {
        Toast.makeText(getActivity(), "onTabReselect&position--->" + position, Toast.LENGTH_SHORT).show();
    }

    @Override
    public void onDestroyView() {
        super.onDestroyView();
    }


    //保存Fragments
    public Map<Integer, Fragment> fragmentMap = new HashMap<>();
    private Fragment tempFragment = null;

    public class MyFragmentPagerAdapter extends FragmentPagerAdapter {

        public MyFragmentPagerAdapter(FragmentManager fm) {
            super(fm);
        }

        @Override
        public Fragment getItem(int position) {


            if (fragmentMap.get(position) == null) {
                if (channelDataList.get(position).getChannelName().equals("推荐")) {
                    tempFragment = FragmentRecommendLayzed.getInstance(channelDataList.get(position).getCode(), channelDataList.get(position).getChannelName(), getActivity());

                } else if (channelDataList.get(position).getChannelName().equals("成果转化")) {
                    tempFragment = FragmentAchievements.getInstance(channelDataList.get(position).getChannelName(), getActivity());

                } else if (channelDataList.get(position).getChannelName().equals("关注")) {
                    tempFragment = FragmentFollow.getInstance(channelDataList.get(position).getChannelName(), getActivity());

                } else if (channelDataList.get(position).getChannelName().equals("世界标准日")) {
                    tempFragment = FragmentStandard.getInstance(channelDataList.get(position).getChannelName(), getActivity());

                } else if (channelDataList.get(position).getChannelName().equals("培训")) {
                    tempFragment = FragmentCultivate.getInstance(channelDataList.get(position).getChannelName(), getActivity());

                } else if (channelDataList.get(position).getChannelName().equals("问答")) {
                    tempFragment = FragmentWenDa.getInstance(channelDataList.get(position).getChannelName(), getActivity());

                } else {
                    tempFragment = FragmentRecommendLayzed.getInstance(channelDataList.get(position).getCode(), channelDataList.get(position).getChannelName(), getActivity());
                }

                fragmentMap.put(position, tempFragment);
            } else {
                tempFragment = fragmentMap.get(position);
            }

//            tempFragment = fragmentMap.get(position);
            return tempFragment;
        }


        @Override
        public int getCount() {
            return channelDataList.size();
        }

        @Override
        public void destroyItem(@NonNull ViewGroup container, int position, @NonNull Object object) {
//            super.destroyItem(container, position, object);
        }

        @Override
        public void setPrimaryItem(@NonNull ViewGroup container, int position, @NonNull Object object) {
            mCurrentFragment = (Fragment) object;
            super.setPrimaryItem(container, position, object);
        }

        private Fragment mCurrentFragment;

        public Fragment getCurrentFragment() {
            return mCurrentFragment;
        }
    }

//    public class KnowledgePagerAdapter extends BaseFragmentViewPagerAdapter {
//
//        private Fragment mCurrentFragment;
//
//
//        public KnowledgePagerAdapter(FragmentManager fm) {
//            super(fm);
//        }
//
//        @Override
//        public Fragment getTabFragment(String tab, int position) {
//
//
//            if (fragmentMap.get(position) == null) {
//                if (channelList.get(position).getName().equals("推荐")) {
//                    tempFragment = FragmentRecommend.getInstance(baseResultEntity, channelList.get(position).getName(), getActivity());
//
//                } else if (channelList.get(position).getName().equals("成果转化")) {
//                    tempFragment = FragmentAchievements.getInstance(channelList.get(position).getName(), getActivity());
//
//                } else if (channelList.get(position).getName().equals("关注")) {
//                    tempFragment = FragmentFollow.getInstance(channelList.get(position).getName(), getActivity());
//
//                } else if (channelList.get(position).getName().equals("世界标准日")) {
//                    tempFragment = FragmentFollow.getInstance(channelList.get(position).getName(), getActivity());
//
//                } else if (channelList.get(position).getName().equals("培训")) {
//                    tempFragment = FragmentCultivate.getInstance(channelList.get(position).getName(), getActivity());
//
//                } else if (channelList.get(position).getName().equals("问答")) {
//                    tempFragment = FragmentWenDa.getInstance(channelList.get(position).getName(), getActivity());
//
//                } else {
//                    tempFragment = FragmentRecommend.getInstance(baseResultEntity, channelList.get(position).getName(), getActivity());
//
//                }
//
//                fragmentMap.put(position, tempFragment);
//            } else {
//                tempFragment = fragmentMap.get(position);
//            }
//
//            return tempFragment;
//
//        }
//
//        @Override
//        public void setPrimaryItem(ViewGroup container, int position, Object object) {
//            mCurrentFragment = (Fragment) object;
//            super.setPrimaryItem(container, position, object);
//        }
//
//
//        public Fragment getCurrentFragment() {
//            return mCurrentFragment;
//        }
//
//    }


    public void fixedLocationFragment(int fragmentIndex) {
        if (tab_layout != null) {
            tab_layout.setCurrentTab(fragmentIndex);
        }
    }

}
